<template>
  <s-layout title="往期中奖名单">
    <view class="lottery-container">
      <view class="lottery">
        <view
          class="lottery-header"
          :style="{ top: sheep.$platform.device.statusBarHeight + 44 + 'px' }">
          <view class="lottery-header-date" @click="handleStageToggle" v-if="currentStageTitle">
            <view class="current-date">{{ currentStageTitle }}</view>
            <!-- <view class="icon"> -->
               <image
                src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250408/a0c730154c5d8c6ae719ffbc1170f2b7.png"
                mode="widthFix"
              />
            <!-- </view> -->
          </view>
          <view class="lottery-header-serach">
            <view class="search-box">
              <input
                type="text"
                class="search-input"
                @confirm="handleInputSearch"
                v-model="lotteryParams.keyword"
                placeholder="搜索手机号/用户昵称"
              />
              <view class="search-btn" @click="handleInputSearch">搜索</view>
            </view>
            <view class="filter-box" @click="handlePrizeToggle">
              <view>
                <image
                  src="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250326/574748210e349c0ccbe0b3a0f348effc.png"
                  mode="widthFix"
                />
              </view>
            </view>
          </view>
        </view>
        <view class="lottery-body">
          <view class="list">
            <view class="list-item" v-for="item in state.lotteryList" :key="item.user_id">
              <view class="user">{{ item.user.nickname }}</view>
              <view class="phone">{{ formatPhone(item.user.mobile) }}</view>
              <view class="prize">{{ item.product_name }}</view>
              <view class="time">{{ item.create_time }}</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 期数弹窗 -->
      <view class="date-picker-box">
        <uni-popup 
          ref="stagePopupRef" 
          :duration="300"
          :mask-click="true"
          background-color="#fff"
        >
          <view class="popup-content">
            <view class="popup-header">
              <text class="cancel" @tap="handleStageClose">关闭</text>
              <text class="confirm" @tap="handleStageConfirm">选择</text>
            </view>
            <view>
              <view
                v-if="state.stageArr.length === 0"
                style="text-align: center; color: #888; font-size: 28rpx; padding-top: 100rpx;"
              >暂无期数</view>
              <view v-else class="picker">
                <picker-view
                  class="picker-view" 
                  :value="stageVal" 
                  @change="handleStageChange"
                >
                  <picker-view-column>
                    <view class="item prize-item-name" v-for="item in state.stageArr" :key="item.title">{{ item.title }}</view>
                  </picker-view-column>
                </picker-view>
              </view>
            </view>
            
          </view>
        </uni-popup>
      </view>

      <!-- 奖品弹窗 -->
      <view class="date-picker-box">
        <uni-popup 
          ref="prizePopupRef" 
          :duration="300"
          :mask-click="true"
          background-color="#fff"
        >
          <view class="popup-content">
            <view class="popup-header" >
              <text class="cancel" @tap="handlePrizeClose">关闭</text>
              <text class="confirm" @tap="handlePrizeConfirm">选择</text>
            </view>
            <view>
              <view
                v-if="state.prizeArr.length === 0"
                style="text-align: center; color: #888; font-size: 28rpx; padding-top: 100rpx;"
              >暂无奖品</view>
              <view v-else class="picker">
                <picker-view 
                  class="picker-view" 
                  :value="prizeVal" 
                  @change="handlePrizeChange"
                >
                  <picker-view-column>
                    <view class="item prize-item-name" v-for="item in state.prizeArr" :key="item.id">{{ item.name }}</view>
                  </picker-view-column>
                </picker-view>
              </view>
            </view>
            
          </view>
        </uni-popup>
      </view>
    </view>


    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
    <s-empty v-if="state.pagination.total === 0" icon="/static/soldout-empty.png" text="暂无中奖名单"></s-empty>
  </s-layout>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  import { onLoad, onReachBottom, onShow, onHide } from '@dcloudio/uni-app';

  import sheep from '@/sheep';
  // 状态定义
  let state = reactive({
    lotteryList: [],
    stageArr: [],
    prizeArr: [],
    pagination: {
      current_page: 1,
      last_page: 1,
      total: 0,
    },
    loadStatus: '', // 加载更多状态 ['more' | 'noMore']
  });

  let lotteryParams = reactive({
    page: 1,
    list_rows: 20, // 每页20条数据
    id: '0', // 期数id
    product_id: '', // 奖品id
    keyword: '', // 模糊匹配关键字
  })

  let prizeVal = reactive([0]) // 回显奖品picker
  let prizeID = ref('') // 暂时保存奖品id，在picker change的时候

  let stageVal = reactive([0]) // 回显期数picker
  let stageID = ref('') // 暂时保存期数id，在picker change的时候

  const stagePopupRef = ref(null)
  const prizePopupRef = ref(null)

  const currentStageTitle = ref('') // 当前期数title
  const indicatorStyle = ref(`height: 40rpx;`)

  const resetData = () => {
    state.lotteryList = []
    state.pagination = {
      current_page: 1,
      last_page: 1,
      total: 0
    }
    state.loadStatus = ''
    lotteryParams.page = 1
  }

  const handlePrizeChange = (e) => {
    const val = e.detail.value
    console.log(val[0])
    console.log(typeof state.prizeArr[val[0]].id)
    console.log(state.prizeArr[val[0]].id, 'prizeArrid')
    prizeID.value = Number(state.prizeArr[val[0]].id)
    prizeVal = val
   
    console.log(prizeVal, 'prizeVal=====')
    console.log(typeof prizeVal, 'prizeVal=====')
  }
  const handlePrizeConfirm = () => {
    console.log(state.prizeArr, 'state.prizeArr')
    console.log(state.prizeArr[0], 'state.prizeArr')
    lotteryParams.product_id = prizeID.value || Number(state.prizeArr[0]?.id)

    resetData()
    getPrevLotteryRecord()
    handlePrizeClose()
  }

  const handleStageChange = (e) => {
    const val = e.detail.value
    console.log(val[0])
    console.log(typeof state.stageArr[val[0]].id)
    console.log(state.stageArr[val[0]].id, 'stageArrid')
    stageID.value = Number(state.stageArr[val[0]].id)
    stageVal = val
   
    console.log(stageVal, 'prizeVal=====')
  }
  const handleStageConfirm = () => {
    lotteryParams.id = stageID.value
    lotteryParams.product_id = ''

    resetData()
    getPrevLotteryRecord()
    handleStageClose()
  }

  // 搜索框
  const handleInputSearch = () => {
    resetData()
    getPrevLotteryRecord()
  }

  // 获取奖品档期select
  const getLotteryStage = async () => {
    try {
      const { error, data } = await sheep.$api.prize_week.lotterysupplierDayPeriods()
      console.log(error, 'error')
      console.log(data, '获取奖品档期select')
      if (error == 0) {
        state.stageArr = data

        console.log(state.stageArr, '获取奖品档期select')

        currentStageTitle.value = data[0]?.title
        lotteryParams.id = data[0]?.id
        stageID.value = data[0]?.id
        return data
      }
    } catch (error) {
      console.error('获取奖品档期select失败:', error)
      throw error // 抛出错误以便上层捕获
    }
  }

  // 往期中奖名单
  const getPrevLotteryRecord = async () => {
    try {
      const { error, data } = await sheep.$api.prize_week.lotterysupplierDayopenLog(lotteryParams)
      if (error == 0) {
        const { total, current_page, last_page } = data
        console.log(current_page, 'current_page')

        if (current_page === 1) {
          state.lotteryList = data.data;
        } else {
          // 如果是加载更多，则追加数据
          state.lotteryList = [...state.lotteryList, ...data.data]
        }
        

        Object.assign(state.pagination, { total, current_page, last_page })

        if (state.pagination.current_page < state.pagination.last_page) {
          state.loadStatus = 'more';
        } else {
          state.loadStatus = 'noMore';
        }

        console.log(data, '用户中奖名单')
        return data.data
      }
    } catch (error) {
      throw error
    }
  }

  // 获取奖池中的奖品记录
  const getPoolLotteryList = async () => {
    try {
      const { error, data } = await sheep.$api.prize_week.lotterysupplierDayPool()
      if (error == 0) {
        state.prizeArr = data
        return data
      }
    } catch (e) {
       throw error
    }
  }

  const loadmore = () => {
    if (state.loadStatus !== 'noMore') {
      state.pagination.current_page ++ 
      lotteryParams.page ++ 
      getPrevLotteryRecord();
    }
  }

  onLoad(async () => {
    state.lotteryList = []
    // 往期select
    await getLotteryStage()
    // 往期中奖名单
    await getPrevLotteryRecord()
    // 获取奖池中的奖品记录
    await getPoolLotteryList()
   
  });

  onShow(async () => {
    state.lotteryList = []
    
    // 往期select
    await getLotteryStage()
    // 往期中奖名单
    await getPrevLotteryRecord()
    // 获取奖池中的奖品记录
    await getPoolLotteryList()
    
  });

  onReachBottom(() => {
    console.log('触底了。')
     loadmore()
  });
   
  const handleStageToggle = () => {
    stagePopupRef.value.open('bottom')
  }
  const handleStageClose = () => {
    stagePopupRef.value?.close()
  }

  const handlePrizeToggle = () => {
    prizePopupRef.value.open('bottom')
  }
  const handlePrizeClose = () => {
    prizePopupRef.value?.close()
  }

  /**
   * @description 将手机号****隐藏部分号码
   * @param phone 手机号
   */
  const formatPhone = (phone) => {
    if (!phone || phone.length !== 11) return phone
    return phone.substring(0, 3) + '****' + phone.substring(7)
  }

</script>

<style lang="less" scoped>
@import './style/business-lottery-list-week.scss';
</style>
